//
//  BoxConfirmViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-11.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "SeatConfirmViewController.h"
#import "SelectDishViewController.h"
#import "OrderDetailViewController.h"
#import "ShopHomeViewController.h"
#import "RelationSeatViewController.h"

#define CELL_HEIGHT 36

@implementation SeatConfirmViewController

#pragma 初始化
- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[SeatConfirmViewController class]];
    if (self) {
        self.shopId = shopId;
        _dataSource = [[SeatConfirmDataSource alloc] initWithVC:self];
        [_dataSource fetchDishOrders];
    }
    return self;
}

#pragma 视图加载完成
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

#pragma 页面显示前隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

#pragma 页面消失前隐藏tabbar
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

#pragma 初始化UI工作
- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"订单确认"];
    
    _dishOrderTable.delegate = _dataSource;
    _dishOrderTable.dataSource = _dataSource;

    [UIView leftMarin:5 withViews:@[_dinnerCountTF,_otherNameTF,_otherPhoneTF]];
    [UIView drawBorders:@[_headView,_bodyView,_otherNameTF,_otherPhoneTF] borderWidth:1];
    [UIView drawBorders:@[_line1,_line2,_line3,_line4,_line5] borderWidth:0.5];
    _otherView.hidden = YES;
    
    [self setFormValues];
    [self reLayoutSubviews];
    [self.view addTarget:self action:@selector(tapGestureAction:)];
}

- (void)leftButtonClick:(id)sender
{
    if (self.orderSuccess) {
        [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
        [self pushOrPopViewController:[ShopHomeViewController class]];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma 填充视图值
- (void)setFormValues
{
    NSString *shopName = [_shopEntity objectForKey:@"name"];
    [_shopNameBtn setTitle:shopName forState:UIControlStateNormal];
    
    NSString *time = [_seatEntity objectForKey:@"time"];
    NSString *zaowan = [_seatEntity objectForKey:@"zaowan"];
    NSString *dinnerTime = [NSString stringWithFormat:@"%@ %@",time,zaowan];
    _dinnerTimeLabel.text = dinnerTime;
    
    _seatNameLabel.text = [self getSeatNames];
    _myPhoneLabel.text = [AppSetting tel];
}

#pragma 获取所有座位名称
- (NSString *)getSeatNames
{
    NSString *seatNames = [NSString stringWithFormat:@"%@: ", [_seatEntity objectForKey:@"zwtype"]];
    NSArray *array = [_seatEntity objectForKey:@"zuowei"];
    for (NSDictionary *seat in array) {
        if ([[seat objectForKey:@"selected"] intValue] == 1) {
            seatNames = [seatNames stringByAppendingFormat:@"%@ ",[seat objectForKey:@"zwname"]];
        }
    }
    return seatNames;
}

#pragma 点击手势回调函数
- (void)tapGestureAction:(id)sender
{
    [_otherPhoneTF resignFirstResponder];
    [_otherNameTF resignFirstResponder];
    [_dinnerCountTF resignFirstResponder];
}

#pragma 开始编辑的时候防止键盘挡住文本框
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    float scrollHeight = [textField topWithLevel:textField.tag]-15;
    [self.theScrollview setContentOffset:CGPointMake(0, scrollHeight) animated:YES];
}

#pragma 退出编辑的时候恢复键盘位置
- (IBAction)TextField_DidEndOnExit:(id)sender
{
    [sender resignFirstResponder];
    [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma 跳转到商户主页面
- (IBAction)goShopHomeAction:(id)sender
{
    BOOL exists = [self existsControllerWithClass:[ShopHomeViewController class]];
    if (exists) {
        [self pushOrPopViewController:[ShopHomeViewController class]];
    }
}

#pragma 选择电话号码
- (IBAction)selPhoneAction:(id)sender
{
    _selMyPhoneBtn.selected = _selOtherBtn.selected = NO;
    [sender setSelected:YES];
    
    _otherView.hidden = !_selOtherBtn.selected;
    
    [self reLayoutSubviews];
}

#pragma 选择性别
- (IBAction)selGenderAction:(id)sender
{
    _sirBtn.selected = _ladyBtn.selected = NO;
    [sender setSelected:YES];
}

#pragma 提交订单
- (IBAction)doneAction:(id)sender
{
    if (![self checkForm]) return;
    
    NSString *caipin = [self getDishOrder];
    
    if ([caipin isEqualToString:@""] && _dataSource.dishOrderList.count > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"系统提示" message:@"您未选择已点菜品订单" delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回选择",@"继续提交", nil];
        alert.tag = 1001;
        [alert show];
    }
    else {
        [self submitOrder];
    }
}

- (void)submitOrder
{
    NSString *username = [AppSetting userName];
    NSString *shopId = [_shopEntity objectForKey:@"id"];
    NSString *seatIds = [self getSeatIds];
    NSString *seatType = [_seatEntity objectForKey:@"zwtype_id"];
    NSString *dinnerCount = _dinnerCountTF.text;
    NSString *orderTime = [_seatEntity objectForKey:@"time"];
    NSString *zaowan = [_seatEntity objectForKey:@"zaowan_id"];
    NSString *tel = _selMyPhoneBtn.selected ? [AppSetting tel] : _otherPhoneTF.text;
    NSString *caipin = [self getDishOrder];
    NSString *otherName = _otherNameTF.text;
    NSString *gender = (_sirBtn.selected ? @"先生" : @"女士");
    
    NSString *url = [NSString stringWithFormat:API_SEAT_ORDER,username,shopId,seatIds,seatType,dinnerCount,orderTime,zaowan,tel,caipin,otherName,gender];
    [_dataSource submitOrderWithURL:url];
}

#pragma 检查数据是否正确
- (BOOL)checkForm
{
    if ([_dinnerCountTF.text isEqualToString:@""]) {
        [AppDelegate showMessage:@"请填写就餐人数！"];
        return NO;
    }
    if (!_selMyPhoneBtn.selected && !_selOtherBtn.selected) {
        [AppDelegate showMessage:@"请选择预订人的手机号码！"];
        return NO;
    }
    if (_selOtherBtn.selected) {
        if ([_otherNameTF.text isEqualToString:@""]) {
            [AppDelegate showMessage:@"请填写其他预订人的姓氏！"];
            return NO;
        }
        if ([_otherPhoneTF.text isEqualToString:@""]) {
            [AppDelegate showMessage:@"请填写其他预订人的电话号码！"];
            return NO;
        }
        if (!_sirBtn.selected && !_ladyBtn.selected) {
            [AppDelegate showMessage:@"请选择其他预订人的性别！"];
            return NO;
        }
    }
    
    return YES;
}

#pragma 获取所选座位的ID
- (NSString*)getSeatIds
{
    int count = 0;
    NSString *seatIds = @"";
    NSArray *array = [_seatEntity objectForKey:@"zuowei"];
    NSMutableArray *selectSeats = [NSMutableArray array];
    for (NSDictionary *seat in array) {
        if ([[seat objectForKey:@"selected"] intValue] == 1) {
            [selectSeats addObject:seat];
        }
    }
    
    for (NSDictionary *seat in selectSeats) {
        if (count == array.count-1) {
            seatIds = [seatIds stringByAppendingFormat:@"%@",[seat objectForKey:@"zid"]];
        }else {
            seatIds = [seatIds stringByAppendingFormat:@"%@,",[seat objectForKey:@"zid"]];
        }
        
        count++;
    }
    return seatIds;
}

- (NSString*)getDishOrder
{
    for (NSDictionary *dic in _dataSource.dishOrderList) {
        int selected =[[dic objectForKey:@"selected"] intValue];
        if (selected == 1) {
            return [dic objectForKey:@"danhao"];
        }
    }
    return @"";
}

- (void)selectFinished:(NSMutableDictionary *)dic
{
    [_dishOrderTable reloadData];
}

#pragma 预定成功后，显示对话框
- (void)orderDidSuccess:(NSDictionary *)data
{
    self.orderSuccess = YES;
    self.orderId = [data objectForKey:@"order_id"];
    
    if (![[self getDishOrder] isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"系统提示" message:@"您的订单预定成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 1002;
        [alert show];
    }
    else {
        AlertWindowView *alert = [[AlertWindowView alloc] initWithMessage:@"恭喜您已预定成功" delegate:self buttonTitles:@[@"查看订单",@"继续点菜"]];
        [self.view addSubview:alert];
        
        [alert showWindow];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001) {
        if (buttonIndex == 1) [self submitOrder];
    }
    
    if (alertView.tag == 1002) {
        OrderDetailViewController *orderVC = [[OrderDetailViewController alloc] initWithOrderId:self.orderId andType:NewOrder];
        [self pushViewController:orderVC];
    }
}

- (void)alertWindow:(AlertWindowView *)alertWindow clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        OrderDetailViewController *orderVC = [[OrderDetailViewController alloc] initWithOrderId:_orderId andType:NewOrder];
        [self pushViewController:orderVC];
    }
    
    if (buttonIndex == 1) {
        [_dataSource checkHaveSeat];
    }
}

#pragma 根据状态跳转到不同的页面，状态1:已预定座位，跳转到关联座位页面
#pragma 状态2:没有预定座位，跳转到点菜页面
- (void)goForState:(int)state
{
    if (state == 1) {
        RelationSeatViewController *comfirmVC = [[RelationSeatViewController alloc] initWithShopId:_shopId];
        [self.navigationController pushViewController:comfirmVC animated:YES];
    }
    if (state == 2) {
        SelectDishViewController *selectDishVC = [[SelectDishViewController alloc] initWithShopId:_shopId];
        [self.navigationController pushViewController:selectDishVC animated:YES];
    }
}

- (void)reLayoutSubviews
{
    [_dishOrderTable reloadData];
    
    _dishOrderTable.hidden = _selDishTextLabel.hidden = _line3.hidden =
    _dataSource.dishOrderList.count == 0;
    
    [_dishOrderTable autoHeightNoMargin];
    
    [UIView autoHeights:@[_headView, _bodyView]];
    [UIView autoLayoutVertical:@[_headView, _bodyView, _submitBtn]];
    [_theScrollview autoHeight];
}

@end

//========================================================================================
#pragma===================================================================================
//========================================================================================

#define DISH_ORDERS_TAG 1001
#define SEAT_SUBMIT_TAG 1002
#define CHECK_HAVE_SEAT_TAG 1003

@implementation SeatConfirmDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _dishOrderList = [[NSArray alloc] init];
    }
    
    return self;
}

- (void)fetchDishOrders
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_DISH_ORDERS,_viewController.shopId,[AppSetting userName]];
    [self get:url tag:DISH_ORDERS_TAG];
}

- (void)submitOrderWithURL:(NSString*)url
{
    [SVProgressHUD show];
    [self get:url tag:SEAT_SUBMIT_TAG];
}

#pragma 检查是否有座位
- (void)checkHaveSeat
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_CHECK_HAVE_SEAT, _viewController.shopId,[AppSetting userName]];
    [self get:url tag:CHECK_HAVE_SEAT_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    
    CLog(@"%@",request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == DISH_ORDERS_TAG) {
        self.dishOrderList = [json objectForKey:@"caipin"];
        [_viewController reLayoutSubviews];
    }
    
    if (request.tag == SEAT_SUBMIT_TAG) {
        int state = [[json objectForKey:@"state"] intValue];
        if (state == 1) {
            [self.viewController orderDidSuccess:json];
        }
        
        if (state == 2) {
            [AppDelegate showMessage:@"座位预定失败!"];
        }
        
        if (state == 3) {
            [AppDelegate showMessage:@"您所选的座位已被其他人预定!"];
        }
    }
    
    if (request.tag == CHECK_HAVE_SEAT_TAG) {
        int state = [[json objectForKey:@"state"] intValue];
        [_viewController goForState:state];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dishOrderList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"DishOrdersCell";
    
    DishOrdersCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    cell.delegate = self.viewController;
//    [Functions disabledDelaysContentTouches:cell];
    
    NSMutableDictionary *dic = [self.dishOrderList objectAtIndex:indexPath.row];
    [cell setContent:dic allDishs:_dishOrderList];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected:111111");
    NSMutableDictionary *row = [_dishOrderList objectAtIndex:indexPath.row];
    int selected = [[row objectForKey:@"selected"] intValue];
    selected = selected == 0 ? 1 : 0;
    [row setObject:INT_TO_STR(selected) forKey:@"selected"];
    
    for (NSMutableDictionary *dic in _dishOrderList) {
        if (![row isEqualToDictionary:dic]) {
            [dic setObject:@"0" forKey:@"selected"];
        }
    }
    
    [_viewController selectFinished:row];

}


@end

